<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
    @click="() => eventHandler.trigger('点击事件')"
  >
    <span class="image-box">
      <el-image
        v-if="imageUrl !== ''"
        preview-teleported
        hide-on-click-modal
        :src="imageUrl"
        :preview-src-list="[imageUrl]"
        style="width:100%;height:100%"
        fit="contain"
      />
    </span>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject, getCurrentInstance } from 'vue'
import api from "@/http/api";
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object
});
const initializing = ref(true);
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const loading = ref(true);
const message = ref('');
const imageUrl = ref('');

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  await nextTick(() => initializing.value = false);
};

const loadValue = async() => {
  const dataList = (await visual.loadData(currNode.value.compData, eventHandler, getData(), currNode.value)).data || [];
  message.value = dataList.length > 0 && dataList[0]['内容'] || '';
  loading.value = true;
  api.createQrCode(message.value).then((res) => {
    loading.value = false;
    imageUrl.value = URL.createObjectURL(new Blob([res.data]));
  }).catch(() => {
    loading.value = false;
  });
};

const getData = () => {
  return { inputParam: currNode.value.inputParam || {}, value: message.value };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await loadValue();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await loadValue();
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped>
.image-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.image-box img {
  max-width: 100%;
  max-height: 100%;
}
</style>